import { checkboxPropsType } from "@/types/props"
import commonStyles from './common.module.scss'
import { FC, useEffect, useState } from "react"
import classNames from "classnames"


const QuestionCheckbox: FC<checkboxPropsType> = ({ fe_id,props }) => {
  const { options, title = '', isVertical } = props
  const [selectedLabels,setSelectedLabels] = useState<string[]>([])

  useEffect(()=>{
    options.forEach(option=>{
      const {label,checked} = option
      if(checked){
        setSelectedLabels(selectedLabels=>selectedLabels.concat(label))
      }
    })
  },[options])

  const toggleChecked = (label:string)=>{
    if(selectedLabels.includes(label)){
      setSelectedLabels(selectedLabels=>selectedLabels.filter(v=>v!==label))
    }else{
      setSelectedLabels(selectedLabels.concat(label))
    }
  }

  const Style = classNames({
    [commonStyles.verticalItem]: isVertical,
    [commonStyles.horizontalItem]: !isVertical,
  })

  return (
    <div className={commonStyles.container}>
      <div className={commonStyles.title}>{title}</div>
      <input type="hidden" name={fe_id} value={selectedLabels.toString()}/>
      <div className={commonStyles.list}>
        <ul className={commonStyles.radioList}>
          {options.map(({value, label}, index) => (
            <li key={index} className={Style}>
              <input type="checkbox" checked={selectedLabels.includes(label)}  onChange={()=>toggleChecked(label)}/>
              <label htmlFor={value}>{label}</label>
            </li>

          ))}
        </ul>
      </div>

    </div>
  )
}


export default QuestionCheckbox